package cc.md888.app.utils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public final class DateTimeUtils {

    /**
     * 时间格式
     */
    public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /**
     * 时间格式中文
     */
    public static final String DATE_TIME_FORMAT_CN = "yyyy年MM月dd HH:mm:ss";

    /**
     * 日期格式
     */
    public static final String DATE_FORMAT = "yyyy-MM-dd";

    /**
     * 日期格式
     */
    public static final String DATE_FORMAT_CN = "yyyy年MM月dd";


    /**
     * 判断时间格式是否正确
     *
     * @param datetime
     * @param format
     * @return
     */
    public static boolean isFormatted(String datetime, String format) {

        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
            formatter.parse(datetime);
            return true;
        } catch (DateTimeParseException e) {
            return false;
        }

    }


    /**
     * string to LocalDateTime
     * @param datetime
     * @param datetime
     * @return
     */
    public static LocalDateTime toLocalDateTime(String datetime){
        if (!isFormatted(datetime, DATE_TIME_FORMAT)) {
            throw new IllegalStateException("时间格式不正确");
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT);
        return LocalDateTime.from(formatter.parse(datetime));
    }

    /**
     * string to LocalDateTime
     * @param datetime
     * @param format
     * @return
     */
    public static LocalDateTime toLocalDateTime(String datetime, String format) {
        if (!isFormatted(datetime, format)) {
            throw new IllegalStateException("时间格式不正确");
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        return LocalDateTime.from(formatter.parse(datetime));
    }

    /**
     * 时间格式化
     *
     * @param time
     * @param pattern
     * @return
     */
    public static String format(LocalDateTime time, String pattern) {
        return DateTimeFormatter.ofPattern(pattern).format(time);
    }

    /**
     * 时间格式化
     *
     * @param time
     * @return
     */
    public static String format(LocalDateTime time) {
        return format(time, DATE_TIME_FORMAT);
    }
}

